package org.jeecg.modules.demo.sopayorder.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.pubuyorder.service.IPuBuyOrderService;
import org.jeecg.modules.demo.sopayorder.entity.SoPayorder;
import org.jeecg.modules.demo.sopayorder.service.ISoPayorderService;
import org.jeecg.modules.demo.util.BigDecimalUtil;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

 /**
 * @Description: so_payorder
 * @Author: jeecg-boot
 * @Date:   2021-12-18
 * @Version: V1.0
 */
@Api(tags="so_payorder")
@RestController
@RequestMapping("/sopayorder/soPayorder")
@Slf4j
public class SoPayorderController extends JeecgController<SoPayorder, ISoPayorderService> {
	@Autowired
	private ISoPayorderService soPayorderService;
	 @Autowired
	 private ISysBaseAPI sysBaseAPI;
	 @Autowired
	 private IPuBuyOrderService puBuyOrderService;


	 /**排序列*/
	 private static final String ORDER_COLUMN = "column";
	 /**排序方式*/
	 private static final String ORDER_TYPE = "order";
	 private static final String ORDER_TYPE_ASC = "ASC";
	 private static final String ORDER_TYPE_DESC = "DESC";
	/**
	 * 分页列表查询
	 *
	 * @param soPayorder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	 @AutoLog(value = "付款单-分页列表查询")
	 @ApiOperation(value="付款单-分页列表查询", notes="付款单-分页列表查询")
	 @GetMapping(value = "/list")
	 @PermissionData(pageComponent="yunxiao/sopayorder/SoPayorderList")
	 public Result<?> queryPageList(SoPayorder soPayorder,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 try{
			 QueryWrapper<SoPayorder> queryWrapper = QueryGenerator.initQueryWrapper(soPayorder, req.getParameterMap());
			 queryWrapper.eq("SHANCHU",0);
			 queryWrapper.eq("BUS_TYPE",0);
			 Page<SoPayorder> page = new Page<SoPayorder>(pageNo, pageSize);
			 IPage<SoPayorder> pageList = soPayorderService.pageList(page, queryWrapper);
			 return Result.OK(pageList);
		 }catch (Exception e){
			 e.printStackTrace();
			 return Result.error(300,"网络故障！");
		 }
	 }

	/**
	 *   添加
	 *
	 * @param soPayorder
	 * @return
	 */
	@AutoLog(value = "付款单-添加")
	@ApiOperation(value="付款单-添加", notes="付款单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody SoPayorder soPayorder,HttpServletRequest req) {
		try{
			String tenantId = req.getHeader("tenant-id");
			String precode = puBuyOrderService.getTeantCodeById(Integer.parseInt(tenantId)).toUpperCase();
			if(soPayorder.getSfamount().doubleValue()<=0){
				return Result.error(300,"付款金额不能为0！");
			}
			soPayorder.setTradecode(soPayorder.getTradecode()!=null?soPayorder.getTradecode():"");
			String str = soPayorderService.getMaxCode();
			Map<String, String> map = new HashMap<>();
			map.put("maxCode", str==null?null:str);
			String name =precode+ "FK_";
			String resultCode = generateOddUtil.createCode(map, name);
			soPayorder.setSopNo(resultCode);
			soPayorder.setShanchu(0);
			soPayorder.setShenhe(0);
			soPayorder.setId(null);
			soPayorder.setCreateTime(new Date());
			if(soPayorderService.addSoPayOrder(soPayorder,precode)){
				return Result.OK("成功！");
			}
			return Result.error(300,"网络故障！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}
	 /**
	  * 审核
	  *
	  * @param soPayorder
	  * @return
	  */
	 @AutoLog(value = "付款单-审核")
	 @ApiOperation(value="付款单-审核", notes="付款单-审核")
	 @PostMapping(value = "/checkSoPayOrder")
	 public Result<?> checkSoPayOrder(@RequestBody SoPayorder soPayorder) {
		 try{
			 // 获取登录用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 if(!sysUser.getId().equals(soPayorder.getSaleman())){
				 return Result.error(500,"您不是当前单据的指定审核人！");
			 }
			 if(soPayorder.getShenhe()==1){
				 return Result.error(300,"单据已审核，请勿重复审核！");
			 }
			 if(soPayorderService.checkSoPayOrder(soPayorder)){
				 return Result.OK("审核成功!");
			 }

			return Result.error(500,"审核失败！");
		 }catch (Exception e){
			 e.printStackTrace();
			 return Result.error(500,"系统错误！");
		 }
	 }

	 @PostMapping(value = "/getDkOrder")
	 public String getDkOrder(@RequestBody SoPayorder soPayorder) {
		 Gson gson = new Gson();
		 Map map = new HashMap();
		 try{
			 List<SoPayorder> payorders = new ArrayList<>();
			 SoPayorder payorder = soPayorderService.getBySopNo(soPayorder.getYfdkorder());
			 payorders.add(payorder);
			 map.put("code",200);
			 map.put("message","查询成功！");
			 map.put("payorders",payorders);
			 String json = gson.toJson(map);
			 return json;
		 }catch (Exception e){
			 e.printStackTrace();
			 map.put("code",500);
			 map.put("message","系统错误！");
			 String json = gson.toJson(map);
			 return json;
		 }
	 }


	 /**
	  *  弃审
	  *
	  * @param soPayorder
	  * @return
	  */
	 @AutoLog(value = "付款单-弃审")
	 @ApiOperation(value="付款单-弃审", notes="付款单-弃审")
	 @PostMapping(value = "/unCheckSoPayOrder")
	 public Result<?> unCheckSoPayOrder(@RequestBody SoPayorder soPayorder) {
		 try{
			 // 获取登录用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 if(!sysUser.getId().equals(soPayorder.getSaleman())){
				 return Result.error(500,"您不是当前单据的指定审核人！");
			 }
		 	if(soPayorder.getShenhe()==0){
		 		return Result.error(300,"请先审核单据！");
			}

			 soPayorder.setShTime(null);
			 soPayorder.setShenhe(0);
			 soPayorderService.updateById(soPayorder);
			 return Result.OK("弃审成功!");
		 }catch (Exception e){
		 	e.printStackTrace();
		 	return Result.error(500,"系统错误！");
		 }
	 }

	/**
	 *  编辑
	 *
	 * @param soPayorder
	 * @return
	 */
	@AutoLog(value = "付款单-编辑")
	@ApiOperation(value="付款单-编辑", notes="付款单-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody SoPayorder soPayorder,HttpServletRequest req) {
		try{
			String tenantId = req.getHeader("tenant-id");
			String precode = puBuyOrderService.getTeantCodeById(Integer.parseInt(tenantId)).toUpperCase();
			if(soPayorder.getShenhe()==1){
				return Result.error(300,"单据已审核，无法编辑！");
			}
			SoPayorder payorder = soPayorderService.getById(soPayorder.getId());
			double sumje;
			if(soPayorder.getPuiNo()!=null){
				sumje= soPayorderService.getSumJe(soPayorder.getPuiNo());
			}else{
				sumje= soPayorderService.getQCyfSumJe(soPayorder.getQcyfNo());
			}
			double syje = BigDecimalUtil.sub(soPayorder.getSopAmount().doubleValue(),sumje);
			double je = BigDecimalUtil.add(syje,payorder.getSfamount().doubleValue());
			if(soPayorder.getSfamount().doubleValue()>je){
				return Result.error(300,"修改后的付款金额不能大于本单金额与剩余可付款金额的和！");
			}
			if(soPayorderService.editPayOrder(soPayorder,precode)){
				return Result.OK("编辑成功!");
			}
			return Result.error(300,"网络故障！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "付款单-通过id删除")
	@ApiOperation(value="付款单-通过id删除", notes="付款单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try{
			SoPayorder soPayorder = soPayorderService.getById(id);
			if(soPayorder.getShenhe()==1){
				return Result.error(300,"单据已审核，无法删除！");
			}
			if(soPayorder.getBusType()==2){
				return Result.error(300,"该单为预付款单抵扣，无法直接删除！");
			}
			if(soPayorderService.delPayOrder(soPayorder)){
				return Result.OK("删除成功!");
			}
			return Result.error(300,"网络故障！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "付款单-批量删除")
	@ApiOperation(value="付款单-批量删除", notes="付款单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.soPayorderService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "付款单-通过id查询")
	@ApiOperation(value="付款单-通过id查询", notes="付款单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		SoPayorder soPayorder = soPayorderService.getById(id);
		if(soPayorder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(soPayorder);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param soPayorder
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SoPayorder soPayorder) {
        return super.exportXls(request, soPayorder, SoPayorder.class, "so_payorder");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SoPayorder.class);
    }

}
